package com.topscomm.center.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.topscomm.file.FileSystemConst;
import com.topscomm.pub.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.topscomm.center.controller.auto.FileManageControllerAuto;
import com.topscomm.center.pojo.FileManageEntity;
import com.topscomm.center.util.FileCenterUtil;
import com.topscomm.core.factory.FileStoreFactoryService;
import com.topscomm.file.FileInfoDTO;
import com.topscomm.file.FileProperties;
import com.topscomm.file.FileSystemConst.FileUploadStateEnum;
import com.topscomm.file.convert.aspose.AsposeFileConvertToHtml;
import com.topscomm.file.service.FileDownloadFilter;
import com.topscomm.file.service.FileUploadFilter;
import com.topscomm.file.util.Utils;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.ParameterCache;

/**
 * 第三方共享文件
 *
 * @description:
 * @author: donghang
 * @date: 2021年7月2日上午11:34:44
 * @modify:
 */
@RestController
@RequestMapping("center/shareFile")
public class FileShareController extends FileManageControllerAuto implements IFileManageController {
	/**
	 * 文件服务类
	 */
	@Autowired
	private FileStoreFactoryService fileStoreFactoryService;
	/**
	 * 文件属性
	 */
	@Autowired
	private FileProperties fileProperties;


	/**
	 * 查询文件url
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2021年4月6日上午11:28:44
	 * @modify:
	 */
	@GetMapping(value = "/queryShowFileUrl")
	public ResponseResult<Object> queryShowFileUrl(@RequestParam Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		String appKey = ConvertUtil.convertToString(paraMap.get("appkey"));
		if (!this.judgePermission(appKey)) {
			return ResponseResult.error("权限不合法");
		}
		// 检查参数
		if (ConvertUtil.convertToString(paraMap.get("qry_identifier")).length() == 0) {
			return ResponseResult.error("参数不完整");
		}
		// 查询文件信息
		List<FileManageEntity> fileList = this.service
				.queryByWhere("identifier='" + ConvertUtil.convertToString(paraMap.get("qry_identifier")) + "'");
		if (fileList.size() == 0) {
			return ResponseResult.error("没有查询到文件信息");
		}
		FileManageEntity finishFileManageEntity = null;
		for (FileManageEntity fileManageEntity : fileList) {
			String fileState = ConvertUtil.convertToString(fileManageEntity.getUploadstate());
			if (fileState.equals(FileUploadStateEnum.Finish)) {
				finishFileManageEntity = fileManageEntity;
				break;
			}
		}
		if (finishFileManageEntity == null) {
			return ResponseResult.error("文件没有处理完成。请稍后查看");
		}
		if (finishFileManageEntity.getLocation() == null) {
			return ResponseResult.error("文件不存在");
		}
		String videoFormater = ParameterCache.getValue("FileVideoFile", "avi,mov,rmvb,rm,flv,mp4,3gp");
		String fileType = ConvertUtil.convertToString(finishFileManageEntity.getFiletype().toLowerCase());
		String fileName = "";
		FileInfoDTO fileInfoDTO;
		if (videoFormater.contains(fileType)) {
			// 视频文件需要播放mp4格式
			fileName = finishFileManageEntity.getLocation().replace("." + fileType, ".mp4");
			fileInfoDTO = FileCenterUtil.fileEntityConvertToFileServiceDto(finishFileManageEntity, fileName);
			// 视频文件默认设置5个小时
			fileInfoDTO.setExpireTime(ParameterCache.getIntValue(FileSystemConst.VIDEO_SIGNATURE_EXPIRE_TIME, 18000));
			fileInfoDTO.setTimeUnit(TimeUnit.SECONDS);
		} else {
			fileName = finishFileManageEntity.getLocation();
			fileInfoDTO = FileCenterUtil.fileEntityConvertToFileServiceDto(finishFileManageEntity, fileName);
			// 普通文件设置5分钟
			fileInfoDTO.setExpireTime(ParameterCache.getIntValue(FileSystemConst.FILE_SIGNATURE_EXPIRE_TIME, 300));
			fileInfoDTO.setTimeUnit(TimeUnit.SECONDS);
		}
		Map<String, Object> dataMap = new HashMap<>();
		dataMap.put("identifier", finishFileManageEntity.getIdentifier());
		dataMap.put("url", this.fileStoreFactoryService.accessUrl(fileInfoDTO));
		return ResponseResult.ok(dataMap);
	}

	/**
	 * 查询原始文件url
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2021年4月6日上午11:28:44
	 * @modify:
	 */
	@GetMapping(value = "/queryOriginalFileUrl")
	public ResponseResult<Object> queryOriginalFileUrl(@RequestParam Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		String appKey = ConvertUtil.convertToString(paraMap.get("appkey"));
		if (!this.judgePermission(appKey)) {
			return ResponseResult.error("权限不合法");
		}
		// 检查参数
		if (ConvertUtil.convertToString(paraMap.get("qry_identifier")).length() == 0) {
			return ResponseResult.error("参数不完整");
		}
		// 查询文件信息
		List<FileManageEntity> fileList = this.service
				.queryByWhere("identifier='" + ConvertUtil.convertToString(paraMap.get("qry_identifier")) + "'");
		if (fileList.size() == 0) {
			return ResponseResult.error("没有查询到文件信息");
		}
		FileManageEntity finishFileManageEntity = null;
		for (FileManageEntity fileManageEntity : fileList) {
			String fileState = ConvertUtil.convertToString(fileManageEntity.getUploadstate());
			if (fileState.equals(FileUploadStateEnum.Finish)) {
				finishFileManageEntity = fileManageEntity;
				break;
			}
		}
		if (finishFileManageEntity == null) {
			return ResponseResult.error("文件没有处理完成，请稍后查看");
		}
		if (finishFileManageEntity.getLocation() == null) {
			return ResponseResult.error("文件不存在");
		}
		String fileName = finishFileManageEntity.getLocation();
		FileInfoDTO fileInfoDTO = FileCenterUtil.fileEntityConvertToFileServiceDto(finishFileManageEntity, fileName);
		Map<String, Object> dataMap = new HashMap<>();
		dataMap.put("identifier", finishFileManageEntity.getIdentifier());
		// 普通文件设置5分钟
		fileInfoDTO.setExpireTime(ParameterCache.getIntValue(FileSystemConst.DOWN_LOAD_SIGNATURE_EXPIRE_TIME, 300));
		fileInfoDTO.setTimeUnit(TimeUnit.SECONDS);
		dataMap.put("url", this.fileStoreFactoryService.accessUrl(fileInfoDTO));
		return ResponseResult.ok(dataMap);
	}

	/**
	 * 查询html文件url
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2021年5月18日下午5:17:56
	 * @modify:
	 */
	@GetMapping(value = "/queryFileHtmlUrl")
	public ResponseResult<Object> queryFileHtmlUrl(@RequestParam Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		String appKey = ConvertUtil.convertToString(paraMap.get("appkey"));
		if (!this.judgePermission(appKey)) {
			return ResponseResult.error("权限不合法");
		}
		// 检查参数
		if (ConvertUtil.convertToString(paraMap.get("qry_identifier")).length() == 0) {
			return ResponseResult.error("参数不完整");
		}
		// 查询文件信息
		List<FileManageEntity> fileList = this.service
				.queryByWhere("identifier='" + ConvertUtil.convertToString(paraMap.get("qry_identifier")) + "'");
		if (fileList.size() == 0) {
			return ResponseResult.error("没有查询到文件信息");
		}
		FileManageEntity finishFileManageEntity = null;
		for (FileManageEntity fileManageEntity : fileList) {
			String fileState = ConvertUtil.convertToString(fileManageEntity.getUploadstate());
			if (fileState.equals(FileUploadStateEnum.Finish)) {
				finishFileManageEntity = fileManageEntity;
				break;
			}
		}
		if (finishFileManageEntity == null) {
			return ResponseResult.error("文件没有处理完成，请稍后查看");
		}
		if (finishFileManageEntity.getLocation() == null) {
			return ResponseResult.error("文件不存在");
		}
		String fileType = ConvertUtil.convertToString(finishFileManageEntity.getFiletype().toLowerCase());
		String fileName = finishFileManageEntity.getLocation().replace("." + fileType, ".html");
		FileInfoDTO fileInfoDTO = FileCenterUtil.fileEntityConvertToFileServiceDto(finishFileManageEntity, fileName);
		if (!this.fileStoreFactoryService.fileIsExist(fileInfoDTO)) {
			// 不存在，执行下载转换操作
			try {
				Map<String, Object> messageMap = new HashMap<String, Object>();
				messageMap.put("identifier", finishFileManageEntity.getIdentifier());
				messageMap.put("filename", ConvertUtil.convertToString(finishFileManageEntity.getIdentifier() + "."
						+ Utils.getExtension(finishFileManageEntity.getName())));
				messageMap.put("foldername", finishFileManageEntity.getDirpath());
				messageMap.put("bucketname", finishFileManageEntity.getBucketname());
				messageMap.put("storagetype", finishFileManageEntity.getStoragetype());
				// 下载
				FileDownloadFilter fileDownloadFilter = new FileDownloadFilter();
				fileDownloadFilter.doProcess(messageMap, null);
				// 转换
				StringBuilder filePath = new StringBuilder();
				filePath.append(fileProperties.getStorePath()).append("/")
						.append(finishFileManageEntity.getIdentifier()).append("/")
						.append(finishFileManageEntity.getLocation());
				StringBuilder targetFilePath = new StringBuilder();
				targetFilePath.append(fileProperties.getStorePath()).append("/")
						.append(finishFileManageEntity.getIdentifier()).toString();
				AsposeFileConvertToHtml.fileToHtml(finishFileManageEntity.getIdentifier(), filePath.toString(),
						targetFilePath.toString());
				// 上传
				FileUploadFilter fileUploadFilter = new FileUploadFilter();
				fileUploadFilter.doProcess(messageMap, null);
				// 删除文件
				StringBuilder localFileDirPath = new StringBuilder();
				localFileDirPath.append(fileProperties.getStorePath()).append("/")
						.append(ConvertUtil.convertToString(messageMap.get("identifier")));
				com.topscomm.pub.util.FileUtil.deleteDirectory(localFileDirPath.toString(), true);
			} catch (Exception e) {
				return ResponseResult.error("文件转换失败");
			}
		}
		Map<String, Object> dataMap = new HashMap<>();
		dataMap.put("identifier", finishFileManageEntity.getIdentifier());
		// 普通文件设置5分钟
		fileInfoDTO.setExpireTime(ParameterCache.getIntValue(FileSystemConst.DOWN_LOAD_SIGNATURE_EXPIRE_TIME, 300));
		fileInfoDTO.setTimeUnit(TimeUnit.SECONDS);
		dataMap.put("url", this.fileStoreFactoryService.accessUrl(fileInfoDTO));
		return ResponseResult.ok(dataMap);
	}

	/**
	 * 查詢appkey合法性
	 *
	 * @description:
	 * @param paraMap
	 * @param appKey
	 * @return
	 * @author: donghang
	 * @date: 2021年7月2日上午11:41:42
	 * @modify:
	 */
	private boolean judgePermission(String appKey) {
		if (StringUtil.isEmpty(appKey)) {
			return false;
		}
		// 查询当前文件拥有的标签
		return this.service.selectExecute("select id from CustomerManage where appkey='" + appKey + "'").size() > 0
				? true : false;
	}

	@GetMapping(value = "/queryViewFileUrl")
	public ResponseResult<Object> queryViewFileUrl(@RequestParam Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			// 检查参数
			if (ConvertUtil.convertToString(paraMap.get("qry_identifier")).length() == 0) {
				return ResponseResult.error("参数不完整");
			}
			String page = ConvertUtil.convertToString(paraMap.get("page"));
			page = StringUtil.isEmpty(page) ? "1" : page;
			int total = ConvertUtil.convertToInt(paraMap.get("total"));
			total = total == 0 ? 1 : total;
			// 查询文件信息
			List<FileManageEntity> fileList = this.service
					.queryByWhere("identifier='" + ConvertUtil.convertToString(paraMap.get("qry_identifier")) + "'");
			if (fileList.size() == 0) {
				return ResponseResult.error("没有查询到文件信息");
			}
			FileManageEntity finishFileManageEntity = null;
			for (FileManageEntity fileManageEntity : fileList) {
				String fileState = ConvertUtil.convertToString(fileManageEntity.getUploadstate());
				if (fileState.equals(FileUploadStateEnum.Finish)) {
					finishFileManageEntity = fileManageEntity;
					break;
				}
			}
			if (finishFileManageEntity == null) {
				return ResponseResult.error("文件没有处理完成。请稍后查看");
			}
			if (finishFileManageEntity.getLocation() == null) {
				return ResponseResult.error("文件不存在");
			}
			String filePath = finishFileManageEntity.getDirpath();

			FileInfoDTO fileInfo = new FileInfoDTO();
			fileInfo.setStorageType(finishFileManageEntity.getStoragetype());
			fileInfo.setBucketName(finishFileManageEntity.getBucketname());
			fileInfo.setFileDirPath(filePath);
			fileInfo.setFileId(finishFileManageEntity.getIdentifier());
			// 普通文件设置5分钟
			fileInfo.setExpireTime(ParameterCache.getIntValue(FileSystemConst.FILE_SIGNATURE_EXPIRE_TIME, 300));
			fileInfo.setTimeUnit(TimeUnit.SECONDS);
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("identifier", finishFileManageEntity.getIdentifier());
			int imageTotalCount = finishFileManageEntity.getImagecount();
			dataMap.put("imagecount", imageTotalCount);
			List<Map<String, String>> list = new ArrayList<>();
			Map<String, String> map;
			total = Math.min(imageTotalCount, total);
			for (int i = 0; i < total; i++) {
				map = new HashMap<>();
				int tempPage = ConvertUtil.convertToInt(page) + i;
				String tempName = finishFileManageEntity.getIdentifier() + "_" + imageTotalCount + "_" + tempPage + ".png";
				fileInfo.setFileName(tempName);
				map.put("url", this.fileStoreFactoryService.accessUrl(fileInfo));
				map.put("index", ConvertUtil.convertToString(tempPage));
				list.add(map);
			}
			dataMap.put("list", list);
			return ResponseResult.ok(dataMap);
		} catch (Exception e) {
			return ResponseResult.error("请重试！");
		}
	}
}
